<?php

/**
 * Subclass for representing a row from the 'blog' table.
 *
 * 
 *
 * @package lib.model
 */ 
class Blog extends BaseBlog
{
    /**
     * 
     * deletes unused Blogs by status id = -1, MyConstants::UNDEFINED_ID
     */
    public static function cleanUnused()
    {
        $c = new Criteria();
        $c->add(BlogPeer::STATUS_ID, MyConstants::UNDEFINED_ID);
        $c->add(BlogPeer::CREATED_AT, time()-(7 * 24 * 60 * 60), Criteria::LESS_EQUAL);
        $con = Propel::getConnection();
        BasePeer::doDelete($c, $con);
    }
    /**
     * 
     * retrieves array of articles by users tag
     * @param unknown_type $tagId
     * @param unknown_type $userId
     */
    public static function getRssItemsForTag($slugName, $userNick = '' )
    {
        $c = new Criteria();
        $c->add(BlogPeer::STATUS_ID, MyConstants::STATUS_APPROVED);
        if( $userNick != '' )
        {
            $tagIds = Tag::getIdsByTag($slugName, $userNick);
            $c->add(BlogPeer::USER_ID, User::getIdByNick($userNick));
            
        }else 
        {
            $tagIds = Tag::getIdsByTag($slugName);
        }
        $i = 0;
        foreach( $tagIds as $tag )
        {
            if($i == 0)
                $criterion = $c->getNewCriterion(BlogPeer::TAGS_LIST, BlogPeer::TAGS_LIST . ' REGEXP "[[:<:]]' . $tag . '[[:>:]]"', Criteria::CUSTOM);
            else
            {
                $criterion->addOr($c->getNewCriterion(BlogPeer::TAGS_LIST, BlogPeer::TAGS_LIST . ' REGEXP "[[:<:]]' . $tag . '[[:>:]]"', Criteria::CUSTOM));
            }
            $i++;
        }
        $c->add($criterion);
        //$c->add(BlogPeer::TAGS_LIST, BlogPeer::TAGS_LIST . ' REGEXP "[[:<:]]' . $tagId . '[[:>:]]"', Criteria::CUSTOM);
        $c->addDescendingOrderByColumn(BlogPeer::CREATED_AT);
        $arBlogs = BlogPeer::doSelect($c);
        $main_url = sfConfig::get('app_main_lturl');
        $start = $main_url . '/blogas/';
        
        $arLinks = array();
        $i=0;
        // select all active posts of user
        foreach( $arBlogs as $blog )
        {
            /* @var $blog Blog */
            $seo= Seo::getSlugByObj($blog->getId(), 'blog', 'show', $blog->getCulture());
            if($seo)
            {
                $arLinks[$i]['loc'] = $start . UserPeer::retrieveByPK($blog->getUserId())->getNick() . '/' . $seo;
                $arLinks[$i]['lastmod'] = strtotime($blog->getUpdatedAt());
                $arLinks[$i]['changefreq'] = '';
                $arLinks[$i]['priority'] = '';
                $arLinks[$i]['title'] = strip_tags($blog->getName());
                $arLinks[$i]['description'] = strip_tags($blog->getSummary());
                $arLinks[$i]['guid'] = uniqid(); $i++;
                
            }
        }
        return $arLinks;
    }
    /**
     * 
     * returns seo obj for this blog. if not have, returns null
     * @return null if not found, else seo Obj
     */
    public function getSeo()
    {
        $c = new Criteria();
        $c->add(SeoPeer::OBJ_TYPE, 'blog');
        $c->add(SeoPeer::OBJ_ACTION, 'show');
        $c->add(SeoPeer::OBJ_ID, $this->getId());
        $c->add(SeoPeer::CULTURE, $this->getCulture());
        $seo = SeoPeer::doSelectOne($c);
        return $seo;
    }
    
    
    public function canUserEdit()
    {
        if( has_role_id(MyConstants::ROLE_ADMIN) || ($this->getUserId() == get_user_id()) )
        {
            return true;
        }
        return false;
    }

    /**
     * 
     * @return array with lnks 
     * @param int $id - user id, for sitemap for one user
     * @param boolean $tagsUsed 
     */
    public static function linksByUserId($id, $tagsUsed = true, $blogsUsed = true)
    {
        $main_url = sfConfig::get('app_main_lturl');
        $user = UserPeer::retrieveByPK($id);
        $arLinks = array();
        if( !$user )
        {
            return $arLinks;
        }
        $i = 0;
        $start = $main_url . '/blogas/' . $user->getNick();
        $arLinks[$i]['loc'] = $start;
        $arLinks[$i]['lastmod'] = time();
        $arLinks[$i]['changefreq'] = 'always';
        $arLinks[$i]['priority'] = '1.0';
        $arLinks[$i]['title'] = "blog " . $user->getNick();
        $arLinks[$i]['description'] = sfContext::getInstance()->getI18N()->__('blogRssDescription');
        $arLinks[$i]['guid'] = uniqid();
        $i++;
        if($blogsUsed)
        {
            // select all active posts of user
            $arBlogs = Blog::getActivePostsByUser($id, true);
            foreach( $arBlogs as $blog )
            {
                /* @var $blog Blog */
                $seo= Seo::getSlugByObj($blog->getId(), 'blog', 'show', $blog->getCulture());
                if($seo)
                {
                    $arLinks[$i]['loc'] = $start . '/' . $seo;
                    $arLinks[$i]['lastmod'] = strtotime($blog->getUpdatedAt());
                    $arLinks[$i]['changefreq'] = '';
                    $arLinks[$i]['priority'] = '';
                    $arLinks[$i]['title'] = strip_tags($blog->getName());
                    $arLinks[$i]['description'] = strip_tags($blog->getSummary());
                    $arLinks[$i]['guid'] = uniqid(); $i++;
                    
                }
            }
        }
        // select all active tags (categories) of user
        if( $tagsUsed )
        {
            $arTags = Tag::getActivePostsByUser($id);
            foreach( $arTags as $tag )
            {
                /* @var $tag Tag */
                $arLinks[$tag->getSlugName()]['loc'] = $start . '/tag/' . $tag->getSlugName();
                $arLinks[$tag->getSlugName()]['lastmod'] = strtotime($tag->getUpdatedAt());
                $arLinks[$tag->getSlugName()]['changefreq'] = '';
                $arLinks[$tag->getSlugName()]['priority'] = '0.5';
                $arLinks[$tag->getSlugName()]['title'] = strip_tags($tag->getName());
                $arLinks[$tag->getSlugName()]['description'] = strip_tags($tag->getName());
                $arLinks[$tag->getSlugName()]['guid'] = uniqid(); $i++;
            }
        }
        return $arLinks;
    }
    /**
     * 
     * Blogs by user id, sorted by date or priority
     * @param int $id
     * @param boolean $srtDate
     * @param boolean $srtPriority
     */
    public static function getActivePostsByUser( $id, $srtDate = false, $srtPriority = false )
    {
        $c = new Criteria();
        $c->add(BlogPeer::STATUS_ID, MyConstants::STATUS_APPROVED);
        $c->add(BlogPeer::USER_ID, $id);
        if($srtPriority)
        {
            $c->addDescendingOrderByColumn(BlogPeer::PRIORITY);
        }
        if($srtDate)
        {
            $c->addDescendingOrderByColumn(BlogPeer::CREATED_AT);
        }
        
        return $arBlogs = BlogPeer::doSelect($c);
    }
    public function getChangeStatus()
    {
        $culture = sfContext::getInstance()->getUser()->getCulture();
        if( $this->getStatusId() == MyConstants::STATUS_APPROVED )
        {
            $disable = sfContext::getInstance()->getI18N()->__('disable');
            return '<a href="/test.php/'.$culture.'/blog/disable?id='.$this->getId().'">'.$disable.'</a>';
        }else
        {
            $enable = sfContext::getInstance()->getI18N()->__('enable');
            return '<a href="/test.php/'.$culture.'/blog/enable?id='.$this->getId().'">'.$enable.'</a>';
        }
    }
    
    public function addTag($tagId)
    {
        // Add tag only if blog has not such tag
        if( !$this->hasTag($tagId) )
        {
            // Ensure that each tag is separated whit colon
            $len = strlen($this->tags_list);
            if( $len == 0 )
            {
                $this->setTagsList($tagId . ':');
            }elseif( $this->tags_list[$len - 1] == ':' )
            {
                $this->setTagsList($this->getTagsList() . $tagId . ':');
            }else 
            {
                $this->setTagsList($this->getTagsList() . ':' . $tagId . ':');
            }
            
        }  // END IF ( need to assign tag )
    }
    
    /**
     * Returns whether blog is marked with requested tag 
     *
     * @param integer $tagId ID of tag to check
     * @return boolean
     */
    public function hasTag($tagId)
    {
        if( preg_match("/\\b" . (int)$tagId . "\\b/", $this->tags_list) )
        {
            return true;
        }
        
        return false;
    }
    /**
     * return array with records by tag (approved)
     *
     * @param string $tagId
     * @return object
     */
    public static function getByTag($tagId)
    {
        
        $c = new Criteria();
        $c->add(BlogPeer::STATUS_ID, MyConstants::STATUS_APPROVED);
        $c->add(BlogPeer::TAGS_LIST, BlogPeer::TAGS_LIST . ' REGEXP "[[:<:]]' . $tagId . '[[:>:]]"', Criteria::CUSTOM);
        return BlogPeer::doSelect($c);
        
    }
    /**
     * Removes tag from blog
     *
     * @param integer $tagId tag ID
     */
    public function removeTag($tagId)
    {
        $arTags = explode(':', $this->tags_list);
        $total = count($arTags);
//        debugvar($arTags);
        for( $i = 0; $i < $total; $i++ )
        {
            if( $arTags[$i] == $tagId )
            {
                // Unset tag and exit
                unset($arTags[$i]);
                $i = 1000;
            }
        }
        $this->setTagsList(join(':', $arTags));
        //debugvar('Set tag: ' . $this->getTags());
    }
}
